import numpy as np
from dnn_utils_v2 import *
import matplotlib.pyplot as plt
def init_params(layer_dims):
    params = {}
    L = len(layer_dims)
    for l in range(1,L):
        params['W' + str(l)] = np.random.randn(layer_dims[l],layer_dims[l - 1])*0.01
        params['b' + str(l)] = np.zeros((layer_dims[l],1))*0.01
        assert(params['W' + str(l)].shape == (layer_dims[l],layer_dims[l - 1]))
        assert(params['b' + str(l)].shape == (layer_dims[l],1))
    return params
	
def linear_forward(A_pre,W,b):
    Z = np.dot(W,A_pre) + b
    assert(Z.shape == (W.shape[0],A_pre.shape[1]))
    cache=(A_pre, W, b)
    return Z,cache

def linear_act_forward(A_pre,W,b,activation):	
    Z,linear_cache = linear_forward(A_pre,W,b)

    if activation == "sigmoid":
        A,act_cache = sigmoid(Z)

    elif activation == "relu":
        A,act_cache = relu(Z)

    assert(A.shape == Z.shape)
    cache = (linear_cache,act_cache)
    return A,cache
	
def L_model_forward(X,params):
    caches = []
    A = X
    L = len(params)//2
    for l in range(1,L):
        A_pre = A
        A,cache = linear_act_forward(A_pre,params['W' + str(l)],params['b' + str(l)],'relu')
        caches.append(cache)
    AL,cache = linear_act_forward(A,params['W' + str(L)],params['b' + str(L)],'sigmoid')
    caches.append(cache)
    assert(AL.shape == (1,X.shape[1]))
    return AL,caches
	
def compute_cost(A,Y):
    m = Y.shape[1]
    cost = -np.sum(Y*np.log(A) + (1 - Y)*np.log(1 - A))/m
    cost = np.squeeze(cost)
    assert(cost.shape == ())
    return cost

def linear_backward(dZ,cache):
    A_pre,W,b = cache
    m = A_pre.shape[1]
    dW = np.dot(dZ,A_pre.T)/m
    db = np.sum(dZ,axis = 1,keepdims = True)/m
    dA_pre = np.dot(W.T,dZ)
    assert(dW.shape == W.shape)
    assert(db.shape == b.shape)
    assert(dA_pre.shape == A_pre.shape)
    return dA_pre,dW,db

def linear_act_backward(dA,cache,activation):
    linear_cache,act_cache = cache
    if activation == 'relu':
        dZ = relu_backward(dA,act_cache)
        dA_pre,dW,db = linear_backward(dZ,linear_cache)
    elif activation == 'sigmoid':
        dZ = sigmoid_backward(dA,act_cache)
        dA_pre,dW,db = linear_backward(dZ,linear_cache)
    return dA_pre,dW,db

def L_model_backward(AL,Y,caches):
    grads = {}
    L = len(caches)
    Y = Y.reshape(AL.shape)
    dAL = -(np.divide(Y,AL) - np.divide(1-Y,1-AL))
    current_cache = caches[L-1]
    grads['dA' + str(L)],grads['dW' + str(L)],grads['db' + str(L)] = linear_act_backward(dAL,current_cache,activation = 'sigmoid')
    for l in reversed(range(L-1)):
        current_cache = caches[l]
        grads['dA' + str(l+1)],grads['dW' + str(l+1)],grads['db' + str(l+1)] = linear_act_backward(grads['dA' + str(l+2)],current_cache,activation = 'relu')
    return grads
    
def update_params(params,grads,learning_rate):
    L = len(params)//2
    for l in range(L):
        params['W' + str(l + 1)] = params['W' + str(l + 1)] - learning_rate*grads['dW' + str(l + 1)]
        params['b' + str(l + 1)] = params['b' + str(l + 1)] - learning_rate*grads['db' + str(l + 1)]
    return params

def predict(X,Y,params):
    m = X.shape[1]
    AL,caches = L_model_forward(X,params)
    for i in range(0,AL.shape[1]):
        if AL[0,i] > 0.5:
            AL[0,i] = 1
        else:
            AL[0,i] = 0
    accuracy = np.sum(abs(AL - Y),axis = 1)/m
    print("准确率为：%f"%accuracy)
    return AL
    
def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):#lr was 0.009
    """
    Implements a L-layer neural network: [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID.
    
    Arguments:
    X -- data, numpy array of shape (number of examples, num_px * num_px * 3)
    Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)
    layers_dims -- list containing the input size and each layer size, of length (number of layers + 1).
    learning_rate -- learning rate of the gradient descent update rule
    num_iterations -- number of iterations of the optimization loop
    print_cost -- if True, it prints the cost every 100 steps
    
    Returns:
    parameters -- parameters learnt by the model. They can then be used to predict.
    """
    np.random.seed(1)
    costs = []                         # keep track of cost
    
    # Parameters initialization.
    ### START CODE HERE ###
    parameters = init_params(layers_dims)
    ### END CODE HERE ###
    
    # Loop (gradient descent)
    for i in range(0, num_iterations):
        # Forward propagation: [LINEAR -> RELU]*(L-1) -> LINEAR -> SIGMOID.
        ### START CODE HERE ### (≈ 1 line of code)
        AL, caches = L_model_forward(X,parameters)
        ### END CODE HERE ###
        
        # Compute cost.
        ### START CODE HERE ### (≈ 1 line of code)
        cost = compute_cost(AL,Y)
        ### END CODE HERE ###
    
        # Backward propagation.
        ### START CODE HERE ### (≈ 1 line of code)
        grads = L_model_backward(AL,Y,caches)
        ### END CODE HERE ###
 
        # Update parameters.
        ### START CODE HERE ### (≈ 1 line of code)
        parameters = update_params(parameters,grads,learning_rate)
        ### END CODE HERE ###
                
        # Print the cost every 100 training example
        if print_cost and i % 100 == 0:
            print ("Cost after iteration %i: %f" %(i, cost))
        if print_cost and i % 100 == 0:
            costs.append(cost)            
    # plot the cost
    plt.plot(np.squeeze(costs))
    plt.ylabel('cost')
    plt.xlabel('iterations (per tens)')
    plt.title("Learning rate =" + str(learning_rate))
    plt.show()
    
    return parameters